package com.eagle.videoboot.controller;

import com.eagle.videoboot.domain.entity.Users;
import com.eagle.videoboot.domain.vo.ResultVO;
import com.eagle.videoboot.domain.vo.UsersVO;
import com.eagle.videoboot.service.IUsersService;
import com.eagle.videoboot.utils.JSONResult;
import com.eagle.videoboot.utils.MD5Utils;
import com.eagle.videoboot.utils.ResultVOUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@Api(value="用户注册登录的接口", tags= {"注册和登录的controller"})
public class RegistController {
	
	@Autowired
	private IUsersService usersServiceImpl;


	@ApiOperation(value="用户注册", notes="用户注册的接口")
	@PostMapping("/regist")
	public ResultVO regist(@RequestBody Users user) throws Exception {
		
		// 1. 判断用户名和密码必须不为空
		if (StringUtils.isBlank(user.getUsername()) || StringUtils.isBlank(user.getPassword())) {
			return ResultVOUtil.error("B0003","用户名和密码不能为空");
		}
		
		// 2. 判断用户名是否存在
		boolean usernameIsExist = usersServiceImpl.queryUsernameIsExist(user.getUsername());

		// 3. 保存用户，注册信息
		if (!usernameIsExist) {
			usersServiceImpl.saveUser(user);
		} else {
			return ResultVOUtil.error("B0002","用户名已经存在，请换一个再试");
		}
		
		user.setPassword("");
		UsersVO usersVO = usersServiceImpl.setUserRedisSessionToken(user);
		return ResultVOUtil.success(usersVO);
	}

	@ApiOperation(value="用户登录", notes="用户登录的接口")
	@PostMapping("/login")
	public ResultVO login(@RequestBody Users user) throws Exception {
		String username = user.getUsername();
		String password = user.getPassword();

//		Thread.sleep(3000);

		// 1. 判断用户名和密码必须不为空
		if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
			return ResultVOUtil.error("B0003","用户名和密码不能为空");
		}

		// 2. 判断用户是否存在
		Users userResult = usersServiceImpl.queryUserForLogin(username,
				MD5Utils.getMD5Str(user.getPassword()));

		// 3. 返回
		if (userResult != null) {
			userResult.setPassword("");
			UsersVO userVO = usersServiceImpl.setUserRedisSessionToken(userResult);
			return ResultVOUtil.success(userVO);
		} else {
			return ResultVOUtil.error("B0004","用户名或密码不正确, 请重试...");
		}
	}

	@ApiOperation(value="用户注销", notes="用户注销的接口")
	@ApiImplicitParam(name="userId", value="用户id", required=true,
			dataType="String", paramType="query")
	@PostMapping("/logout")
	public ResultVO logout(String userId) throws Exception {
		usersServiceImpl.delUserRedisSessionToken(userId);
		return ResultVOUtil.success();
	}



}
